;
jQuery.upload = function(options) {

  var defaults = {
    url : "",
    redirect : "",
    data : {},
    multiple : true,
    maxsize : 1024 * 1024 * 20,
    extention : "",
    success : function() {
    }
  };

  var settings = $.extend({}, defaults, options);

  if (settings.url == '') {
    throw 'url is required !';
  }

  var random = Math.random().toString().substr(2);
  var iframeid = 'iframe' + random;
  var formid = 'form' + random;

  var $iframe = $('<iframe />').addClass('cust-upload-component').css('display', 'none')
    .attr('id', iframeid).attr('name', iframeid).appendTo('body');

  var $form = $('<form />').addClass('cust-upload-component').css('display', 'none').attr('method', 'POST')
    .attr('id', formid).attr('name', formid).attr('enctype', 'multipart/form-data')
    .attr('target', iframeid).attr('action', settings.url).appendTo('body');

  for (var key in settings.data) {
    var value = settings.data[key];
    if (key == '_file' || key == '_redirect_url') {
      throw '"_file" and "_redirect_url" is used, please change name !';
    } else if (value instanceof Array) {
      for (var i in value) {
        $('<input />').attr('name', key).val(value[i]).appendTo($form);
      }
    } else {
      $('<input />').attr('name', key).val(value).appendTo($form);
    }
  }
  
  if (settings.redirect != '') {
    $('<input />').attr('name', '_redirect_url').val(settings.redirect).appendTo($form);
  }

  var $file = $('<input name="_file" type="file" multiple="multiple"/>').appendTo($form);
  if(settings.multiple) {
    $file.attr('multiple', 'multiple');
  }
  $file.change(function() {
    for (i in this.files) {
      var file = this.files[i];
      if (file.size > settings.maxsize) {
        alert('file size is too large !');
        return;
      }
    }
    var callback = function() {
      try {
        var result = JSON.parse($('body', $iframe[0].contentWindow.document).html());
        settings.success(result);
      } catch (e) {
        console.log(e);
      }
      setTimeout(function() { 
        $iframe.remove();
        $form.remove();
      }, 100);
    };
    if (window.attachEvent) {
      document.getElementById(iframeid).attachEvent('onload', callback);
    } else {
      document.getElementById(iframeid).addEventListener('load', callback, false);
    }
    $form.submit();
  });
  $file.click();
};
